import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, DatePicker, Popconfirm, Spin, Table, TableProps, Upload, UploadFile } from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';
import { omit } from 'lodash-es';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proDataRawDelete,
  proDataRawDownloadTemplate,
  proDataRawImport,
  proDataRawPage
} from '@/services/bizApi/yuanshuishujujiekou';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProDataRawEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const fileList = useRef<UploadFile[]>([]);
  const [spinning, setSpinning] = useState(false);

  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      let query = {
        ...formData,
        ...id,
        rqBegin: formData.rq ? dayjs(formData.rq?.[0]).format('YYYY-MM-DD') : undefined,
        rqEnd: formData.rq ? dayjs(formData.rq?.[1]).format('YYYY-MM-DD') : undefined,
        page: current,
        size: pageSize
      };
      query = omit(query, 'rq');
      const res = await proDataRawPage(query);

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const handleImport = useRequest(
    async () => {
      setSpinning(true);
      const formData = new FormData();
      formData.append('file', fileList.current[0].originFileObj!);

      await proDataRawImport({} as ArgumentsType<typeof proDataRawImport>[0], {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: formData,
        timeout: 60000
      }).finally(() => {
        setSpinning(false);
      });

      store.app?.message.success('导入成功');
      table.search.submit();
    },
    {
      manual: true
    }
  );

  const rowSelection: TableProps<BizObject>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: BizObject[]) => {
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedRows(selectedRowKeys);
    }
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
            {permission.check() && (
              <Button
                onClick={async () => {
                  const res = await proDataRawDownloadTemplate({
                    skipErrorHandler: true,
                    responseType: 'blob'
                  });
                  Saver.saveAs(res?.data, '污水数据分析模板.xlsx');
                }}
                type="primary"
              >
                下载模板
              </Button>
            )}
            {permission.check() && (
              <Upload
                maxCount={1}
                accept=".xls,.xlsx"
                showUploadList={false}
                beforeUpload={() => false}
                fileList={fileList.current}
                onChange={(info) => {
                  fileList.current = info.fileList;
                  if (fileList.current.length) {
                    handleImport.run();
                  }
                }}
              >
                <Button type="primary">导入</Button>
              </Upload>
            )}
          </>
        }
      >
        <Filter.Item name="rq">
          <DatePicker.RangePicker placeholder={['日期', '日期']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>

        {selectedRows.length > 0 && permission.check() && (
          <Filter.Item>
            <Popconfirm
              title={`确定要批量删除吗？`}
              onConfirm={async () => {
                const res = await proDataRawDelete({
                  id: selectedRows.join(',')
                });
                store.app?.message.success(res.message);
                table.refresh();
                setSelectedRows([]);
              }}
            >
              <Button type="primary" danger>
                批量删除
              </Button>
            </Popconfirm>
          </Filter.Item>
        )}
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        rowSelection={{ type: 'checkbox', ...rowSelection }}
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '日期',
            dataIndex: 'rq',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          { title: '当日进水量', dataIndex: 'drjsl' },
          {
            title: '当日供水量',
            dataIndex: 'drgsl'
          },
          {
            title: '当日用电量',
            dataIndex: 'drydl'
          },
          {
            title: '排泥量',
            dataIndex: 'pnl'
          },
          {
            title: '餐厨厂',
            dataIndex: 'ccc'
          },
          {
            title: '固废公司',
            dataIndex: 'gfgs'
          },
          {
            title: '综合管理区（绿化）',
            dataIndex: 'zhglq'
          },
          {
            title: '市公司接驳区',
            dataIndex: 'sgsjbq'
          },
          {
            title: '桂湾',
            dataIndex: 'gw'
          },
          {
            title: '餐厨污水厂',
            dataIndex: 'ccwsc'
          },
          {
            title: '洛碛渗滤液',
            dataIndex: 'lqcyy'
          },
          {
            title: '供水合计',
            dataIndex: 'gshj'
          },
          {
            title: '清水池库存量',
            dataIndex: 'qsckcl'
          },
          {
            title: '生产异常情况说明',
            dataIndex: 'scycqksm'
          },
          {
            title: '聚氯化铝饮用水级',
            dataIndex: 'jlhlyysj'
          },
          {
            title: '阳离子聚丙烯酰胺2',
            dataIndex: 'ylzjbxya2'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              function equDefectAcceptanceSubmit(arg0: { id: string }) {
                throw new Error('Function not implemented.');
              }

              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() =>
                        edit.current!.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        })
                      }
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该条数据吗？`}
                      onConfirm={async () => {
                        const res = await proDataRawDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success('删除成功');
                        table.refresh();
                      }}
                    >
                      <Text>删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />

      <Spin spinning={spinning} tip="数据导入中..." size="large" fullscreen />
    </>
  );
};

export default Page;
